<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\console\command\make\Model;
use think\Request;

use function PHPSTORM_META\type;

class User extends Backend
{
    public function __construct()
    {
        parent::__construct();
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
    }

    public function index()
    {
        // 获取所有用户数据  分页
        $UserList = model('User.User')->order('createtime')->paginate(4, false, ['query' => Request::instance()->param()]);

        // 条件搜索
        if ($this->request->isGet()) {
            $action = $this->request->param('action');
            if ($action == 'search') {
                $params = $this->request->param();
                if ($params['search'] == 'nickname') {
                    $UserList = $this->UserModel->where('nickname', 'LIKE','%'.$params['title'].'%')->paginate(4, false, 
                    ['query' => Request::instance()->param()]);
                } 
            }
            if ($action == 'search') {
                $params = $this->request->param();
                if ($params['search'] == 'email') {
                    $UserList = $this->UserModel->where('email', 'LIKE','%'.$params['title'].'%')->paginate(4, false, 
                    ['query' => Request::instance()->param()]);
                } 
            }
            if ($action == 'search') {
                $params = $this->request->param();
                if ($params['search'] == 'sex') {
                    if ($params['title'] == '男') {
                        $text = '1';
                    } elseif ($params['title'] == '女') {
                        $text = '2';
                    } else {
                        $text = '0';
                    }
                    $UserList = $this->UserModel->where('sex', $text)->paginate(4, false, 
                    ['query' => Request::instance()->param()]);
                } 
            }
        }
        $navTitle = '用户管理';
        $navSmall = '用户列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'UserList' => $UserList
        ]);
    }

    // 新增用户
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->param();
            // halt($params);
            $findemail = model('User.User')->where('email', $params['email'])->find();
            if ($findemail) {
                $this->error('该账号已存在');
            }

            if ($params['password'] != $params['repassword']) {
                $this->error('密码不一致');
            }

            // 生成密码盐
            $salt = build_ranstr();

            // 密码加密
            $pwd = md5($params['password'] . $salt);

            $avatar = upload('avatar');
            // halt($avatar);
            if ($avatar['code'] == 0) {
                $this->error($avatar['msg']);
            }
            
            $point = model('config')->where('key', 'RegisterPoint')->value('value');
            $data = [
                'email' => $params['email'],
                'password' => $pwd,
                'nickname' => $params['nickname'],
                'avatar' => $avatar['data'],
                'salt' => $salt,
                'sex' => $params['sex'],
                'auth' => 0,
                'vip' => 1,
                'point' => $point
            ];
            
            $res = $this->UserModel->validate('common/User/User')->save($data);
            if ($res == false) {
                @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
                $this->error($this->UserModel->getError());
            } else {
                @is_file('.' . $this->LoginUser['avatar']) && unlink('.' . $this->LoginUser['avatar']);
                $this->success('新增成功', url('admin/user/index'));
            }
        }

        return $this->fetch();
    }

    // 删除用户
    public function del() {
        $userid = $this->request->param('id');
        // halt($userid['id']);
        $user = model('User.User')->where('id', $userid)->find();
        // halt($user);
        if (!$user) {
            $this->error('该用户无法删除');
        }
        $res = $this->UserModel->destroy($userid);
        if ($res == false) {
            $this->error('该用户删除失败');
        }
        $this->success('该用户删除成功', url('admin/user/index'), null, 2);

    }

    // 编辑用户
    public function edit() {
        $id = $this->request->param('id');
        $user = model('User.User')->find($id);
        // halt($user);
        if($this->request->isPost()) {

        }
        return $this->fetch('', [
            'user' => $user
        ]);
    }

    // 批量删除用户
    public function delAll() {
        if ($this->request->isAjax()) {
            $params = $this->request->param();
            if ($params['list'] == null) {
                $this->error('未知错误');
            }
            $ids = implode(',', $params['list']);
            // halt($ids);
            $res = $this->UserModel->destroy($ids);
            if (!$res) {
                $this->error("批量删除失败");
            } 
            $this->success("批量删除成功", url('admin/user/index'), null, 2);
        }
    }

    // 查看单个用户积分记录
    public function record() {
        
        $id = $this->request->param('userid');
        // halt($id);
        $recordList = null;
        $flag = false;
        $user = null;
        $num = null;
        if($id == null) {
            $recordList =  $this->RecordModel->with('user')->whereNotIn('state', 3)->order('createtime', 'desc')->paginate(10, false, ['query' => Request::instance()->param()]);
            $flag = false;
        } else {
            $user = $this->UserModel->find($id);
            if (!$user) {
                $this->error('无权限查看');
            }
            $recordList =  $this->RecordModel->with('user')->where('userid', $id)->order('createtime', 'desc')->paginate(10, false, ['query' => Request::instance()->param()]);
            $recordNum =  $this->RecordModel->with('user')->where('userid', $id)->select();
            $flag = true;
            $num = count($recordNum);
        }
        $navTitle = '用户管理';
        $navSmall = '用户消费记录';
        return $this->fetch('', [
            'recordList' => $recordList,
            'flag' => $flag,
            'user' => $user,
            'num' => $num,
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
        ]);
    }

    // 充值记录
    public function recharge () {
        $record = $this->RecordModel->with('user')->where('state', 3)->order('createtime', 'desc')->paginate(10, false, ['query' => Request::instance()->param()]);;
        if (!$record) {
            $this->error('查询失败');
        }

        // 条件搜索
        if ($this->request->isGet()) {
            $action = $this->request->param('action');
            $params = $this->request->param();
            if ($action == 'search') {
                if ($params['search'] == 'nickname') {
                    $record = $this->RecordModel->with('user')->where('user.nickname', 'LIKE','%'.$params['title'].'%')->order('createtime', 'desc')
                    ->paginate(10, false, ['query' => Request::instance()->param()]);
                } 
            }
        }

        if ($this->request->isAjax()) {
            if ($this->request->isPost()) {
                $action = $this->request->param('action');

                // 通过审核
                if ($action == 'recharge1') {
                    $id = $this->request->param('id');
                    $Record = $this->RecordModel->where('state', 3)->find($id);
                    $user = $this->UserModel->find($Record['userid']);
                    if (!$Record) {
                        $this->error('记录不存在');
                    }
                     // 开启事务
                    $this->UserModel->startTrans();
                    $this->RecordModel->startTrans();

                    // 更新用户积分
                    $pointValue = bcadd($user['point'], $Record['point']);
                    $UserData = [
                        "id" => $user['id'],
                        "point" => $pointValue,
                    ];
                    $UserState = model("User.User")->isUpdate(true)->save($UserData);
                    if ($UserState == false) {
                        $this->error('审核失败');
                    }

                    // 新增用户消费表数据
                    $RecordData = [
                        "id" => $id,
                        "userid" => $Record['userid'],
                        "point" => $Record['point'],
                        "state" => 3,
                        "flag" => 1,
                        "content" => "您" . "【充值】的" . $Record['point'] . "积分，通过审核，已成功到账。" 
                    ];
                    // halt($RecordData);
                    $RecordState = $this->RecordModel->isUpdate(true)->save($RecordData);
                    if ($RecordState == false) {
                        $this->error('审核失败');
                    }
                   
                    if ($UserState == false || $RecordState == false) {
                        $this->UserModel->rollback();
                        $this->RecordModel->rollback();
                        $this->error('审核失败', null, null);
                    } else {
                        $this->UserModel->commit();
                        $this->RecordModel->commit();
                        $this->success('审核成功', null, null);
                    }
                }

                // 未通过审核
                if ($action == 'recharge2') {
                    $id = $this->request->param('id');
                    $Record = $this->RecordModel->where('state', 3)->find($id);
                    // $user = $this->UserModel->find($Record['userid']);
                    if (!$Record) {
                        $this->error('记录不存在');
                    }
                     // 开启事务
                    // $this->UserModel->startTrans();
                    // $this->RecordModel->startTrans();

                    // 更新用户积分
                    // $pointValue = bcsub($user['point'], $Record['point']);
                    // $UserData = [
                    //     "id" => $user['id'],
                    //     "point" => $pointValue,
                    // ];
                    // $UserState = model("User.User")->isUpdate(true)->save($UserData);
                    // if ($UserState == false) {
                    //     $this->error('审核失败');
                    // }

                    // 新增用户消费表数据
                    $RecordData = [
                        "id" => $id,
                        "userid" => $Record['userid'],
                        "point" => $Record['point'],
                        "state" => 3,
                        "flag" => 2,
                        "content" => "您" . "【充值】的" . $Record['point'] . "积分，未通过审核，已成功退回。" 
                    ];
                    $RecordState = $this->RecordModel->isUpdate(true)->save($RecordData);
                    if ($RecordState == false) {
                        // $this->UserModel->rollback();
                        $this->error('审核失败');
                    }
                    $this->success('审核成功', null, null);
                   
                    // if ($UserState == false || $RecordState == false) {
                    //     $this->UserModel->rollback();
                    //     $this->RecordModel->rollback();
                    //     $this->error('审核失败', null, null);
                    // } else {
                    //     $this->UserModel->commit();
                    //     $this->RecordModel->commit();
                    //     $this->success('审核成功', null, null);
                    // }
                }

            }
        }

        $navTitle = '用户管理';
        $navSmall = '用户充值记录';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'record' => $record
        ]);
    }

    // 回收站
    public function recovery() {

        // 获取回收站列表数据
        $RecoveryList = model('User.User')->onlyTrashed()->order('createtime', 'desc')->paginate(5, false, ['query' => Request::instance()->param()]);
        // halt($RecoveryList);
        if ($this->request->isPost()) {
            $action = $this->request->param('action');
            // 删除
            if ($action == 'del') {
                $id = $this->request->param('id');
                $user = model('User.User')->onlyTrashed()->find($id);
                // halt($user);
                if (!$user) {
                    $this->error('该用户无法恢复，请重试!');
                }
                $res = model('User.User')->destroy($id, true);
                if ($res == false) {
                    $this->error('删除失败');
                }
                $this->success('删除成功');

            }
            // 恢复
            if ($action == 'return') {
                $id = $this->request->param('id');
                $user = model('User.User')->onlyTrashed()->find($id);
                // halt($user);
                if (!$user) {
                    $this->error('该用户无法恢复');
                }
                // 通过删除字段deletetime来恢复数据
                $data = [
                    'id' => $id,
                    'deletetime' => null
                ];
                $res = model("User.User")->isUpdate(true)->save($data);
                if ($res == false) {
                    $this->error('用户恢复失败');
                }
                $this->success('用户恢复成功');

            }
            // 批量删除
            if ($action == 'delAll') {
                $params = $this->request->param();
                $ids = implode(',', $params['list']);
                // halt($ids);
                $res = $this->UserModel->onlyTrashed()->where("id in ($ids)")->delete(true);
                // halt($res);
                if (!$res) {
                    $this->error('批量删除失败');
                } 
                $this->success("批量删除成功", null, null, 2);
            } 
            // 批量恢复
            if ($action == 'returnAll') {
                $params = $this->request->param();
                $data = [];
                foreach($params['list'] as $item) {
                    $arr['id'] = $item;
                    $arr['deletetime'] = null;
                    array_push($data, $arr);
                }
                // halt($data);
                $res = $this->UserModel->isUpdate(true)->saveAll($data);
                // halt($res);
                if (!$res) {
                    $this->error('批量恢复失败');
                } 
                $this->success("批量恢复成功", null, null, 2);

            }
        }
        $navTitle = '用户管理';
        $navSmall = '回收站';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'RecoveryList' => $RecoveryList,
        ]);
    }
}
